//
//
//  HomeManageViewController.m
//  xpkc
//
//  Created by TopSageOSX on 14/12/24.
//  Copyright (c) 2014年 wanmeizty. All rights reserved.
//

#import "ChangeNewsViewController.h"

@interface ChangeNewsViewController ()

@end

@implementation ChangeNewsViewController{
    UIScrollView *scrollView;
    //数据
    NSMutableArray *allArray;
    NSMutableArray *catalogueInArray;
    NSMutableArray *catalogueOutArray;
    //按钮
    NSMutableArray *btnInArray;
    NSMutableArray *btnOutArray;
    
    
    CGPoint startPoint;
    UIButton *tempBtn;
    CGRect tempFrame;
    CGFloat xx;//偏移距离
    CGFloat yy;
    int xP;//偏移单位
    int yP;
    int startIndex;//起始按钮数组位置
    int stopIndex;
    //常用栏目距离顶部高度
    int top;
    //不常用栏目距离顶部距离
    int bottom;
    CGFloat buttonW;//按钮宽度
    CGFloat buttonH;
    int numLine;//每行个数
    CGFloat spaceSize;//间隔大小
    
    UILabel *_label3;
    UILabel *_label4;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"栏目编辑";
    [self creatView];
}
#pragma mark - == creatview ==
/**
 *  创建视图
 */
-(void)creatView{
    if (isPad) {
        spaceSize = 40;
        numLine = 4;
    }else{
        spaceSize = 15;
        numLine = 3;
    }
    top = spaceSize*2;
    bottom = 210;
    
    buttonW = (SCREEN_WIDTH-spaceSize*(numLine+1))/numLine;
    buttonH = buttonW/2;
    
    scrollView = [[UIScrollView alloc]init];
    scrollView.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT-64);
    
    scrollView.showsVerticalScrollIndicator = FALSE;
    scrollView.backgroundColor = BGColor;
    scrollView.userInteractionEnabled = YES;
    
    
    [self.view addSubview:scrollView];
    //开始获取
    [self getLocalCatelogueInfo];
}


/**
 *  界面赋值
 */
-(void)creatHomeBtn{
    
    if (isPad) {
        bottom =((catalogueInArray.count+3)/4)*(buttonH+spaceSize)+100;
    }else{
        bottom =((catalogueInArray.count+2)/3)*(buttonH+spaceSize)+70;
    }
    
    UILabel *label = [[UILabel alloc]init];
    label.text = @"常用栏目·";
    label.frame = CGRectMake(0, 0, 100, 50);
    label.font = [UIFont boldSystemFontOfSize:14];
    [scrollView addSubview:label];
    
    UILabel *label2 = [[UILabel alloc]init];
    label2.text = @"长按可拖动调整栏目顺序";
    label2.frame = CGRectMake(70, 0, 200, 50);
    label2.font = [UIFont systemFontOfSize:12];
    [scrollView addSubview:label2];
    
    _label3 = [[UILabel alloc]init];
    _label3.text = @"其他栏目·";
    _label3.frame = CGRectMake(0, bottom-20, 100, 30);
    _label3.font = [UIFont boldSystemFontOfSize:14];
    [scrollView addSubview:_label3];
    
    _label4 = [[UILabel alloc]init];
    _label4.text = @"点击可添加至常用栏目";
    _label4.frame = CGRectMake(70, bottom-20, 200, 30);
    _label4.font = [UIFont systemFontOfSize:12];
    [scrollView addSubview:_label4];
    
    scrollView.contentSize = CGSizeMake(SCREEN_WIDTH, (catalogueInArray.count+2)/2*(buttonH+spaceSize)+spaceSize);
    logdebug(@"%@",catalogueInArray);
    for (int i = 0; i<catalogueInArray.count; i++) {
        NSDictionary *dic = [catalogueInArray objectAtIndex:i];
        
        HomeButton *homeBtn = [[HomeButton alloc]initWithFrame:CGRectMake(0, 0, buttonW, buttonH)];
        homeBtn.buttonTitle = [dic objectForKey:@"title"];
        homeBtn.enterType = [dic objectForKey:@"enterType"];
        homeBtn.enterIndex = [dic objectForKey:@"index"];
        
        [homeBtn setFrame:CGRectMake(i%numLine*(buttonW+spaceSize)+spaceSize, top+i/numLine*(buttonH+spaceSize)+spaceSize, buttonW, buttonH)];
        [homeBtn addTarget:self action:@selector(catalogueButtonClick:) forControlEvents:UIControlEventTouchUpInside];
        UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc]initWithTarget:self action:@selector(touch:)];
        [homeBtn addGestureRecognizer:longPress];
        [homeBtn isInHome:YES];
        [homeBtn setValue];
        [homeBtn setStyle:HomeButtonStyleLight];
        if (i == 0) {
            [homeBtn setStyle:HomeButtonStyleLightGray];//头条不可选
            homeBtn.userInteractionEnabled = NO;
        }
        if ([[dic objectForKey:@"enterType"] isEqualToString:@"more"]) {
            homeBtn.userInteractionEnabled = NO;
            homeBtn.backgroundColor = [UIColor darkGrayColor];
        }
        
        [btnInArray addObject:homeBtn];
        [scrollView addSubview:homeBtn];
    }
    for (int i = 0; i<catalogueOutArray.count; i++) {
        NSDictionary *dic = [catalogueOutArray objectAtIndex:i];
        
        HomeButton *homeBtn = [[HomeButton alloc]initWithFrame:CGRectMake(0, 0, buttonW, buttonH)];
        homeBtn.buttonTitle = [dic objectForKey:@"title"];
        homeBtn.enterType = [dic objectForKey:@"enterType"];
        homeBtn.enterIndex = [dic objectForKey:@"index"];
        [homeBtn setFrame:CGRectMake(i%numLine*(buttonW+spaceSize)+spaceSize, bottom+i/numLine*(buttonH+spaceSize)+spaceSize, buttonW, buttonH)];
        [homeBtn addTarget:self action:@selector(catalogueButtonClick:) forControlEvents:UIControlEventTouchUpInside];
        UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc]initWithTarget:self action:@selector(touch:)];
        [homeBtn addGestureRecognizer:longPress];
        [homeBtn isInHome:NO];
        [homeBtn setValue];
        [homeBtn setStyle:HomeButtonStyleLight];
        
        [btnOutArray addObject:homeBtn];
        [scrollView addSubview:homeBtn];
    }
}

#pragma mark -
#pragma mark == func ==

/**
 *  获取本地的目录信息
 */
-(void)getLocalCatelogueInfo{
    //初始化
    btnInArray = [NSMutableArray array];
    btnOutArray = [NSMutableArray array];
    allArray = [NSMutableArray array];
    catalogueInArray = [NSMutableArray array];
    catalogueOutArray = [NSMutableArray array];
    logdebug(@"--------%@",self.inArray);
    if (1) {
        catalogueInArray = self.inArray;
        catalogueOutArray = self.outArray;
    }else{
    }
    [self creatHomeBtn];
}

/**
 *  设定位置
 */
- (void)setBtnFrame{
    if (isPad) {
        bottom =((catalogueInArray.count+3)/4)*(buttonH+spaceSize)+100;
    }else{
        bottom =((catalogueInArray.count+2)/3)*(buttonH+spaceSize)+80;
    }
    int j = 0;
    for (int i = 0; i<btnInArray.count; i++) {
        UIButton *btn = [btnInArray objectAtIndex:i];
        //判断是否延时
        if (i%numLine*(buttonW+spaceSize)+spaceSize - btn.frame.origin.x <= 1 &&
            top+i/numLine*(buttonH+spaceSize)+spaceSize - btn.frame.origin.y <= 1) {
            //做差减少误差啊，妈蛋的小数直接比较容易出错的
            //巨坑
        }else{
            j++;
        }
        [UIView animateWithDuration:0.3 delay:j*0.1 options:UIViewAnimationOptionAllowAnimatedContent animations:^{
            [btn setFrame:CGRectMake(i%numLine*(buttonW+spaceSize)+spaceSize, top+i/numLine*(buttonH+spaceSize)+spaceSize, buttonW, buttonH)];
        } completion:^(BOOL finished) {
            //
        }];
    }
    j = 0;
    for (int i = 0; i<btnOutArray.count; i++) {
        UIButton *btn = [btnOutArray objectAtIndex:i];
        //判断是否延时
        if (i%numLine*(buttonW+spaceSize)+spaceSize - btn.frame.origin.x <= 1 &&
            bottom+i/numLine*(buttonH+spaceSize)+spaceSize - btn.frame.origin.y <= 1) {
            //做差减少误差啊，妈蛋的小数直接比较容易出错的
            //巨坑
        }else{
            j++;
        }
        [UIView animateWithDuration:0.3 delay:j*0.1 options:UIViewAnimationOptionAllowAnimatedContent animations:^{
            [btn setFrame:CGRectMake(i%numLine*(buttonW+spaceSize)+spaceSize, bottom+i/numLine*(buttonH+spaceSize)+spaceSize, buttonW, buttonH)];
        } completion:^(BOOL finished) {
            //
        }];
    }
    [UIView animateWithDuration:0.3 animations:^{
        _label3.frame = CGRectMake(0, bottom-20, 100, 30);
        _label4.frame = CGRectMake(70, bottom-20, 200, 30);
    }];
    
}

/**
 *  项目按钮点击
 *
 *  @param btn btn
 */
-(void)catalogueButtonClick:(HomeButton *)btn{
    if ([btnInArray containsObject:btn]) {
        if (btnInArray.count <= 1) {
            //唯一一个
            ShowAlertMsg(@"至少要有一个保留内容");
            return;
        }
        NSUInteger index = [btnInArray indexOfObject:btn];
        [catalogueOutArray addObject:[catalogueInArray objectAtIndex:index]];
        [catalogueInArray removeObjectAtIndex:index];
        [btnOutArray addObject:btn];
        [btnInArray removeObject:btn];
        [btn isInHome:NO];
    }else{
        NSUInteger index = [btnOutArray indexOfObject:btn];
        [btnInArray insertObject:btn atIndex:btnInArray.count];
        [catalogueInArray insertObject:[catalogueOutArray objectAtIndex:index] atIndex:catalogueInArray.count];
        [catalogueOutArray removeObjectAtIndex:index];
        [btnOutArray removeObject:btn];
        [btn isInHome:YES];
    }
    [self setBtnFrame];

}
/**
 *  长按拖动手势
 *
 *  @param ges ges
 */
-(void)touch:(UIGestureRecognizer *)ges{
    NSMutableArray *btnTempArray;
    CGFloat tempTop;
    int btnCount;
    BOOL isIn = NO;
    if ([btnInArray containsObject:ges.view]) {
        logdebug(@"有");
        btnTempArray = btnInArray;
        btnCount = (int)btnInArray.count;
        tempTop = top;
        isIn = YES;
    }else{
        logdebug(@"木有啊");
        btnTempArray = btnOutArray;
        btnCount = (int)btnOutArray.count;
        tempTop = bottom;
        isIn = NO;
    }
    
    if (ges.state == UIGestureRecognizerStateBegan) {
        startPoint = [ges locationInView:scrollView];
        logdebug(@"%f:%f",startPoint.x,startPoint.y);
        startIndex = ((int)startPoint.x/(int)(SCREEN_WIDTH/numLine)*1+(int)(startPoint.y - tempTop)/(int)(buttonH+spaceSize)*numLine);
        tempBtn = [btnTempArray objectAtIndex:startIndex];
        tempBtn.layer.shadowColor = [UIColor blackColor].CGColor;
        tempBtn.layer.shadowOffset = CGSizeMake(5, 5);
        tempBtn.layer.shadowOpacity = 0.4;
        [scrollView bringSubviewToFront:tempBtn];
        tempFrame = tempBtn.frame;
    }else if(ges.state == UIGestureRecognizerStateChanged) {
        CGPoint point = [ges locationInView:scrollView];
        logdebug(@"%f:%f",point.x,point.y);
        tempBtn.frame = CGRectMake(tempFrame.origin.x + point.x - startPoint.x, tempFrame.origin.y + point.y - startPoint.y, buttonW, buttonH);
        int currentP = ((int)point.x/(int)(SCREEN_WIDTH/numLine)*1+(int)(point.y - tempTop)/(int)(buttonH+spaceSize)*numLine);
        if (currentP >= btnTempArray.count) {
            currentP = btnTempArray.count -1;
        }
        if (currentP <= 1) {
            currentP = 1;//不能比头条靠前
        }
        if (currentP == startIndex) {
        }else{
            if (currentP < startIndex) {
                [btnTempArray insertObject:tempBtn atIndex:currentP];
                [btnTempArray removeObjectAtIndex:startIndex+1];
                
                for (int i = currentP+1; i<=startIndex; i++) {
                    UIButton *btn = [btnTempArray objectAtIndex:i];
                    [UIView beginAnimations:nil context:nil];
                    [UIView setAnimationDuration:0.4];
                    [UIView setAnimationDelay:(i-currentP)*0.2];
                    btn.frame = CGRectMake((i)%numLine*(buttonW+spaceSize)+spaceSize, (i)/numLine*(buttonH+spaceSize)+spaceSize+tempTop, buttonW, buttonH);
                    [UIView commitAnimations];
                }
            }else{
                [btnTempArray insertObject:tempBtn atIndex:currentP+1];
                [btnTempArray removeObjectAtIndex:startIndex];
                
                for (int i = startIndex; i<currentP; i++) {
                    UIButton *btn = [btnTempArray objectAtIndex:i];
                    [UIView beginAnimations:nil context:nil];
                    [UIView setAnimationDuration:0.4];
                    [UIView setAnimationDelay:(i-startIndex)*0.2];
                    btn.frame = CGRectMake(i%numLine*(buttonW+spaceSize)+spaceSize, i/numLine*(buttonH+spaceSize)+spaceSize+tempTop, buttonW, buttonH);
                    [UIView commitAnimations];
                }
            }
            startIndex = currentP;
        }
    }else if (ges.state == UIGestureRecognizerStateEnded){
        [UIView beginAnimations:nil context:nil];
        [UIView setAnimationDuration:0.4];
        tempBtn.frame = CGRectMake(startIndex%numLine*(buttonW+spaceSize)+spaceSize, startIndex/numLine*(buttonH+spaceSize)+spaceSize+tempTop, buttonW, buttonH);
        tempBtn.layer.shadowOffset = CGSizeMake(0, 0);
        tempBtn.layer.shadowColor = CCOLOR.CGColor;
        [UIView commitAnimations];
    }
}

/**
 *  保存
 *
 *  @param animated an
 */
-(void)viewWillDisappear:(BOOL)animated{
    logdebug(@"视图消失:保存目录信息");
    //TODO:保存排列好的标签顺序
    //返回按钮数组
    logdebug(@"%@",catalogueInArray);
    self.newsBlock(catalogueInArray,catalogueOutArray);
}

#pragma mark -
#pragma mark == other ==

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
